<blockquote>
    <p>常用类</p>
    <footer>这里会简述全局需要用的一些文件 <code>ResponseCode.java</code> <code>Json.java</code> <code>TipException.java</code>
    </footer>
</blockquote>
<div class="panel panel-default">
    <div class="panel-body">
        <p><b style="color:red">注意</b>：控制层[@Controller] 返回数据的时候, 会根据方法不同的返回类型, 返回不同的结果 如下：</p>
        <p>String 类型：会根据常量里面的配置放回响应的视图类型, 默认是jsp</p>
        <p>Object 类型：当返回Object时候会去掉值为null的属性</p>
        <p>&lt;T&gt 类型：会保留所有属性输出</p>
        <p>Resource 类型：当new Resource("a.txt", data) 时, 可以将resouce下面的文件当做模板进行读取然后响应输出, 例如：druid管理页面, 加强后就是一套模板引擎</p>
        <p>Json 类型：会包装一层响应吗输出</p>
        <div style="margin-left:50px;">
            <p>成功：当Json.success("hello world java!") 时, <code>{"message":"ok","data":"hello world
                java!","code":0}</code></p>
            <p>失败：当Json.fail("code is error!") 时, 或用使用全局枚举 Json.fail(ResponseCode.ARGUMENTS_ERROR), <code>{"message":"code
                is error!","code":107}</code></p>
            <p>数据值为空：当Json.succcess(null) 时, 会报错<code>{"message":"response data is null","code":109}</code></p>
            <p>异常：当Json.exception(ResponseCode.ARGUMENTS_ERROR) 时, 会进行日志记录, 并报错<code>{"message":"request argument is
                error","code":1011}</code></p>
        </div>
    </div>
</div>

<blockquote>
    <p>全局响应吗</p>
    <footer>com.acxy.ants.common.enums.ResponseCode</code>
    </footer>
</blockquote>
<pre class="code brush:java">
package com.acxy.ants.common.enums;

/**
 * 响应码定义
 * Created by MrShun on 2016/7/15.
 */
public enum ResponseCode {

    SUCCESS(0, "ok"),

    TOKEN_EXPIRED_INFO(100, "token is expired"),

    TOKEN_INVALID_INFO(101, "token is invalid"),

    AUTH_INFO(102, "no operation authority"),

    LOGIN_INFO(103, "please log in again"),

    MYSQL_PK_ERROR(104, "the record was referenced, and the operation failed"),

    FILE_MAX_INFO(105, "upload file size out of range"),

    REFRESH_INFO(106, "your refresh is too fast to stand"),

    REQUEST_ERROR(107, "500 program internal error"),

    REQUEST_TYPE_ERROR(108, "405 request type error"),

    DATA_NULL_ERROR(109, "response data is null"),

    NULL_POINT_ERROR(1000, "object null pointer error"),

    ARGUMENTS_ERROR(1011, "request argument is error"),

    UNKNOWN_ERROR(1012, "unknown error"),

    RESTRIC_ERROR(2001, "table data is associated with restrictions"),

    COLUMN_LONG_ERROR(2002, "data too long for column");

    private int code;
    private String msg;

    ResponseCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
</pre>
<blockquote class="clear">
    <p>Json数据返回 <code class="fz13">主要是利用了阿里的 fastjson</code></p>
    <footer>com.acxy.ants.resful.render.Json</code>
    </footer>
</blockquote>
<pre class="code brush:java">
package com.acxy.ants.resful.render;

import com.acxy.ants.common.enums.ResponseCode;
import com.acxy.ants.resful.bean.Page;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Json输出工具
 * @author MrShun
 * @version 1.0
 * @Date 2017-05-04
 */
public class Json {

    //执行状态
    public static final String STATE = "code";

    //消息描述
    public static final String MSG = "message";

    //数据对象
    public static final String RESULT = "data";

    //时间戳
    private static final String TIMESPAN = "time";

    //异常消息
    private static final String ERROR = "exception";

    //当前页数
    private static final String PAGECURRENT = "page";

    //每页大小
    private static final String PAGESIZE = "size";

    //总记录数
    private static final String TOTALCOUNT = "rows";

    //总页数
    private static final String TOTALPAGE = "total";

    /**
     * 操作成功
     *
     * @param data      数据对象
     * @param startTime 开始时间
     * @param &lt;T&gt;
     * @return
     */
    public static &lt;T&gt; Map success(T data, Long startTime) {
        if(data == null) return fail(ResponseCode.DATA_NULL_ERROR);
        Map map = new HashMap();
        map.put(STATE, ResponseCode.SUCCESS.getCode());
        map.put(MSG, ResponseCode.SUCCESS.getMsg());
        if (startTime != null)
            map.put(TIMESPAN, System.currentTimeMillis() - startTime + " msec");
        else if (data.getClass() == Page.class) {
            Page page = ((Page) data);
            map.put(RESULT, page.getData());
            map.put(PAGECURRENT, page.getPage());
            map.put(PAGESIZE, page.getSize());
            map.put(TOTALCOUNT, page.getRows());
            map.put(TOTALPAGE, page.getTotal());
        } else {
            map.put(RESULT, data);
        }
        return map;
    }

    public static &lt;T&gt; Map success(T data) {
        return success(data, null);
    }


    /**
     * 为了适配ui框架
     * @param data
     * @param &lt;T&gt;
     * @return
     */
    public static &lt;T&gt; Map ui(T data) {
        if(data == null) return fail(ResponseCode.DATA_NULL_ERROR);
        Map map = new HashMap();
        map.put(STATE, ResponseCode.SUCCESS.getCode());
        map.put(MSG, ResponseCode.SUCCESS.getMsg());
        if (data.getClass() == Page.class) {
            Page page = ((Page) data);
            map.put("data", page.getData());
            map.put("total", page.getRows());
        } else {
            map.put(RESULT, data);
        }
        return map;
    }
    /**
     * 操作异常失败
     *
     * @param responseCode 枚举响应码
     * @param exception    异常信息
     * @return
     */
    public static Object exception(ResponseCode responseCode, String exception) {
        Map map = new HashMap();
        map.put(STATE, responseCode.getCode());
        map.put(MSG, exception);
        map.put(ERROR, responseCode.getMsg());
        return JSON.toJSON(map);
    }

    public static Object exception(ResponseCode responseCode) {
        Map map = new HashMap();
        map.put(STATE, responseCode.getCode());
        map.put(MSG, responseCode.getMsg());
        return JSON.toJSON(map);
    }

    /**
     * 操作错误
     *
     * @param responseCode 枚举响应码
     * @return
     */
    public static Map fail(ResponseCode responseCode) {
        Map map = new HashMap();
        map.put(STATE, responseCode.getCode());
        map.put(MSG, responseCode.getMsg());
        return map;
    }

    /**
     * 自定义响应吗
     * @param code 响应吗
     * @param msg  消息
     * @return
     */
    public static Map fail(int code, String msg) {
        Map map = new HashMap();
        map.put(STATE, code);
        map.put(MSG, msg);
        return map;
    }

    /**
     * 操作错误自定义错误码
     *
     * @param msg 自定义系统错误消息
     * @return
     */
    public static Map fail(String msg) {
        Map map = new HashMap();
        map.put(STATE, ResponseCode.REQUEST_ERROR.getCode());
        map.put(MSG, msg);
        return map;
    }

    /**
     * 基于PrintWriter返回json数据
     * 可以配置fastjson输出配置
     * http://blog.csdn.net/u010246789/article/details/52539576
     * 常用 SerializerFeature
     * PrettyFormat 格式化输出json
     * WriteNullStringAsEmpty   字符类型字段如果为null,输出为”“,而非null
     * WriteNullBooleanAsFalse	Boolean字段如果为null,输出为false,而非null
     * WriteNullNumberAsZero	数值字段如果为null,输出为0,而非null
     * WriteNullListAsEmpty	List字段如果为null,输出为[],而非null
     * WriteMapNullValue	是否输出值为null的字段,默认为false
     * QuoteFieldNames	输出key时是否使用双引号,默认为true
     * @param data
     * @param response
     */
    public static void writeJson(Object data, HttpServletResponse response, boolean serializers) {
        response.setContentType("application/json;charset=" + response.getCharacterEncoding());
        try {
            PrintWriter w = response.getWriter();
            //返回Response响应数据
            if(serializers)
                JSON.writeJSONStringTo(data, w, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty);
            else
                JSON.writeJSONStringTo(data, w);
            w.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void writeJson(Object data, HttpServletResponse response){
        writeJson(data, response, false);
    }
}
</pre>
<blockquote class="clear">
    <p>异常错误提示</p>
    <footer>com.acxy.ants.core.exception.TipException</code>
    </footer>
</blockquote>
<div class="panel panel-default">
    <div class="panel-body">
        <b style="color:red">注意</b>：该异常只能应用于Ajax请求或者手机请求头进行抛出, 页面直接访问不会显示异常信息
    </div>
</div>
<pre class="code brush:java">
package com.acxy.ants.core.exception;

import com.acxy.ants.core.kit.LogKit;

/**
 * 该异常主要用于在Service层里面做抛出错误提示
 *
 * @author MrShun
 * @version 1.0
 * @Date 2017-08-24
 */
public class TipException extends RuntimeException {

    public TipException() {
        super();
    }

    public TipException(String message) {
        super(message);
    }

    public TipException(Object obj, String message) {
        super(message);
    }

    public TipException(String message, Throwable cause) {
        super(message, cause);
    }

    public TipException(Throwable cause) {
        super(cause);
    }

    @Override
    public void printStackTrace() {
        StackTraceElement stackTraceElement = getStackTrace()[0];
        LogKit.error("错误提示：" + stackTraceElement.toString() + " -> " + getMessage());
    }
}

</pre>
<div class="clear">使用异常抛出错误提示</div>
<pre class="code brush:java">
if(StrKit.isBlank(name))
    throw new TipException("测试 TipException 异常抛出!");
return Json.success(name);
</pre>
<pre class="code brush:javascript">
&lt;script>
    $.get("api/test", function (res) {
        alert(JSON.stringify(res));
    })
&lt;/script>
</pre>
<p class="clear">运行后的效果</p>
<p style="margin-bottom: 100px;"><img src="debug/exception.png"/></p>
<script type="text/javascript">
    $(function () {
        SyntaxHighlighter.highlight();
        $(".toolbar").remove();
    });
</script>